from flask import Blueprint, request, jsonify
import random
import string
from datetime import datetime, timedelta
import os

from .share import app,shared_vars

jobs_bp = Blueprint('jobs', __name__)

def random_string(length=10):
    return ''.join(random.choices(string.ascii_letters, k=length))

def random_time():
    now = datetime.now()
    delta = timedelta(days=random.randint(0, 30), 
                      hours=random.randint(0, 23),
                      minutes=random.randint(0, 59))
    return (now - delta).strftime('%Y-%m-%d %H:%M:%S')

@jobs_bp.route('/list', methods=['GET'])
def get_job_list():
    page_id = request.args.get('page_id', 1)
    env_id = request.args.get('env_id')
    
    jobs = []
    jobs = [job for job in shared_vars['jobs']]
    for _ in range(5):
        status = random.choice(['waitting', 'runing', 'abort', 'finish'])
        jobs.append({
            'job_id'      : random_string(),
            'os'          : random.choice(['windows', 'linux']),
            'submit_time' : random_time(),
            'queue_time'  : random_time(),
            'start_time'  : random_time(),
            'end_time'    : random_time(),
            'cpu'         : 1,
            'memory'      : random.randint(50, 200),
            'status'      : status,
            'progress'    : random.randint(20, 100)
        })
    
    return jsonify({'jobs': jobs})

@jobs_bp.route('/tasks', methods=['GET'])
def get_task_list():
    page_id = request.args.get('page_id', 1)
    job_id = request.args.get('job_id')
    
    tasks = []
    for _ in range(10):
        status = random.choice(['waitting', 'runing', 'abort', 'finish'])
        tasks.append({
            'task_id': random_string(),
            'job_id': random_string(),
            'os': random.choice(['windows', 'linux']),
            'queue_time': random_time(),
            'start_time': random_time(),
            'end_time': random_time(),
            'cpu': 1,
            'memory': random.randint(50, 200),
            'status': status,
            'progress': random.randint(20, 100)
        })
    
    return jsonify({'tasks': tasks})

@jobs_bp.route('/run', methods=['POST'])
def run_job():
    data = request.get_json()
    job_id = data.get('job_id')
    jobs = [job for job in shared_vars['jobs'] if job['job_id']==job_id]
    for job in jobs:
        # 在任意路由或其他地方调用
        socketio = shared_vars['socketio']
        # 全局广播
        socketio.emit("run_script", 
                      {"script": job['script'], 'task_id': random_string()}, 
                      namespace="/api/worker-ws")
    return jsonify({'success': True, 'message': 'Job queued'})

@jobs_bp.route('/abort', methods=['POST'])
def abort_job():
    data = request.get_json()
    job_id = data.get('job_id')
    return jsonify({'success': True, 'message': 'Abort signal sent'})

@jobs_bp.route('/submit', methods=['POST'])
def submit_job():
    env_id = request.form.get('env_id')
    parallel_count = request.files.get('parallel_count')
    parallel_config = request.files.get('parallel_config')
    aggregate_config = request.files.get('aggregate_config')
    
    if parallel_config:
        path_name = os.path.join(app.config['UPLOAD_FOLDER'], parallel_config.filename)
        parallel_config.save(path_name)
    if aggregate_config:
        aggregate_config.save(os.path.join(app.config['UPLOAD_FOLDER'], aggregate_config.filename))

    job = {
        'job_id': 'HK-' + random_string(5),
        'os': 'windows',
        'submit_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'queue_time': '-',
        'start_time': '-',
        'end_time': '-',
        'cpu': 1,
        'memory': random.randint(50, 200),
        'status': 'waitting',
        'progress': 0,
        'script': os.path.abspath(path_name),
    }
    shared_vars['jobs'].append(job)
    
    return jsonify({'success': True, 'message': 'Job submitted'})

@jobs_bp.route('/task-log', methods=['GET'])
def show_task_log():
    task_id = request.args.get('task_id')
    log = ''.join(random.choices(string.ascii_letters + string.digits, k=50))
    return jsonify({'log': log})

@jobs_bp.route('/download-log', methods=['GET'])
def download_task_log():
    task_id = request.args.get('task_id')
    log = ''.join(random.choices(string.ascii_letters + string.digits, k=100))
    return log, 200, {'Content-Type': 'text/plain', 'Content-Disposition': f'attachment; filename={task_id}_log.txt'}
